/*
 *  LucLookupResource
 *
 * Created on 28 November 2008, 16:01
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package luc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import net.sf.json.JSONException;
import javax.ws.rs.QueryParam;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

/**
 * REST Web Service
 *
 * @author hoffmannn
 */

@Path("/luclookup/")
public class LucLookupResource {
    @Context
    private UriInfo context;

    private static Logger log = Logger.getLogger(LucLookupResource.class);

    /** Creates a new instance of LucLookupResource */
    public LucLookupResource() {
    }

    @GET
    @Produces("application/json")
    public String getJson(@QueryParam("att") String att,@QueryParam("lat") String lat,
            @QueryParam("lon") String lon,@QueryParam("srid") int srid) throws JSONException{
        if ((lat == null)||(lon == null))
        {
            return "no result";
        }

        // <editor-fold defaultstate="collapsed" desc="wfs request using httpClient">
        //String wfs="http://localhost:8080/geoserver/wfs?request=GetFeature&version=1.0.0"
        String wfs="http://roj.zen.landcareresearch.co.nz:8080/geoserver/wfs?request=GetFeature&version=1.0.0"
                + "&typeName=lcr:fsl-north-island-all-attributes&outputFormat=GML2"
                + "&FILTER=%3CFilter%20xmlns=%22http://www.opengis.net/ogc%22%20xmlns:gml=%22http://www.opengis.net/gml"
                + "%22%3E%3CIntersects%3E%3CPropertyName%3Ethe_geom%3C/PropertyName%3E%3Cgml:Point%20"
                + "srsName=%22EPSG:"+srid+"%22%3E%3Cgml:coordinates%3E"+lon+","+lat+"%3C/gml:coordinates"
                + "%3E%3C/gml:Point%3E%3C/Intersects%3E%3C/Filter%3E";

        String responseBody="";

        DefaultHttpClient client = new DefaultHttpClient();
        try{
            HttpGet httpget = new HttpGet(wfs);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = client.execute(httpget, responseHandler);

        }catch(IOException ioe){
            log.error(ioe);
        }finally {
            client.getConnectionManager().shutdown();
        }
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="wps request">
        String wps="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> "+
                    "<wps:Execute service=\"WPS\" version=\"1.0.0\" "+
                    "xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" "+
                    "xmlns:ows=\"http://www.opengis.net/ows/1.1\" "+
                    "xmlns:xlink=\"http://www.w3.org/1999/xlink\" "+
                    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "+
                    "xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://geoserver.itc.nl:8080/wps/schemas/wps/1.0.0/wpsExecute_request.xsd\"> "+
                    "<ows:Identifier>tikouka.nl.wps.algorithm.SoilScalingAlgorithm</ows:Identifier> "+
                    "<wps:DataInputs> "+
                    "<wps:Input> "+
                    "<ows:Identifier>fsl</ows:Identifier> "+
                    "<wps:Data> "+
                        "<wps:ComplexData schema=\"http://schemas.opengis.net/gml/2.1.2/feature.xsd\">" +
                    responseBody.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>","") +
                    "</wps:ComplexData> "+
                    "	</wps:Data> "+
                    "</wps:Input> "+
                    "<wps:Input> "+
                    "<ows:Identifier>scalefactor</ows:Identifier> "+
                    "<wps:Data> "+
                    "<wps:ComplexData schema=\"http://tikouka/schemas/RasterTable.xsd\"> "+
                    "<RasterTable name=\"scalefactor\"> "+
                        "<Table id=\"0\" key=\"1,1\" value=\"0.80,1.00,1.00\"/> "+
			"<Table id=\"1\" key=\"1,2\" value=\"0.87,1.44,1.00\"/> "+
			"<Table id=\"2\" key=\"1,3\" value=\"0.95,1.00,1.00\"/> "+
			"<Table id=\"3\" key=\"1,4\" value=\"1.02,1.00,1.00\"/> "+
			"<Table id=\"4\" key=\"1,5\" value=\"1.09,1.80,1.00\"/> "+
			"<Table id=\"5\" key=\"1,6\" value=\"1.16,1.00,1.00\"/> "+
			"<Table id=\"6\" key=\"2,1\" value=\"1.24,1.00,1.00\"/> "+
			"<Table id=\"7\" key=\"2,2\" value=\"1.31,1.00,1.00\"/> "+
			"<Table id=\"8\" key=\"2,3\" value=\"1.38,1.00,1.00\"/> "+
			"<Table id=\"9\" key=\"2,4\" value=\"1.45,1.00,1.00\"/> "+
			"<Table id=\"10\" key=\"2,5\" value=\"1.53,1.20,1.25\"/> "+
			"<Table id=\"11\" key=\"2,6\" value=\"1.60,0.80,1.00\"/> "+
			"<Table id=\"12\" key=\"3,1\" value=\"1.67,1.00,1.00\"/> "+
			"<Table id=\"13\" key=\"3,2\" value=\"1.75,1.80,1.00\"/> "+
			"<Table id=\"14\" key=\"3,3\" value=\"1.76,1.00,1.00\"/> "+
			"<Table id=\"15\" key=\"3,4\" value=\"1.73,1.20,1.00\"/> "+
			"<Table id=\"16\" key=\"3,5\" value=\"1.69,1.00,0.90\"/> "+
			"<Table id=\"17\" key=\"3,6\" value=\"1.62,1.00,1.00\"/> "+
			"<Table id=\"18\" key=\"4,1\" value=\"1.56,1.00,1.00\"/> "+
			"<Table id=\"19\" key=\"4,2\" value=\"1.49,1.00,1.00\"/> "+
			"<Table id=\"20\" key=\"4,3\" value=\"1.42,0.90,1.00\"/> "+
			"<Table id=\"21\" key=\"4,4\" value=\"1.36,1.00,1.00\"/> "+
			"<Table id=\"22\" key=\"4,5\" value=\"1.29,0.70,0.75\"/> "+
			"<Table id=\"23\" key=\"4,6\" value=\"1.22,1.00,1.00\"/> "+
			"<Table id=\"24\" key=\"5,1\" value=\"1.16,1.00,1.00\"/> "+
			"<Table id=\"25\" key=\"5,2\" value=\"1.09,1.00,1.50\"/> "+
			"<Table id=\"26\" key=\"5,3\" value=\"1.02,1.00,1.00\"/> "+
			"<Table id=\"27\" key=\"5,4\" value=\"0.96,1.40,1.00\"/> "+
			"<Table id=\"28\" key=\"5,5\" value=\"0.89,1.20,1.50\"/> "+
			"<Table id=\"29\" key=\"5,6\" value=\"0.82,1.00,1.00\"/> "+
                    "</RasterTable> "+
                    "</wps:ComplexData> "+
                    "</wps:Data> "+
                    "</wps:Input> "+
                    "</wps:DataInputs> "+
                    "<wps:ResponseForm> "+
                    "<wps:ResponseDocument > "+
                    "<wps:Output asReference=\"false\"> "+
                    "<ows:Identifier xmlns=\"http://www.opengis.net/ows/1.1\">result</ows:Identifier> "+
                    "<wps:Reference mimeType=\"xs:string\"/> "+
                    "</wps:Output> "+
                    "</wps:ResponseDocument> "+
                    "</wps:ResponseForm> "+
                    "</wps:Execute> ";
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc="wps request using http Post">
        String res ="";
        HttpResponse response = null;
        DefaultHttpClient client2 = new DefaultHttpClient();
        HttpEntity responseentity=null;
        try{
            HttpPost httppost = new HttpPost("http://localhost:8080/wps/WebProcessingService");
            //HttpPost httppost = new HttpPost("http://roj.zen.landcareresearch.co.nz:8080/wps/WebProcessingService");
            HttpEntity entity = new StringEntity(wps, "application/xml", HTTP.UTF_8);
            httppost.setEntity(entity);
            response = client2.execute(httppost);
            responseentity = response.getEntity();

            res = convertStreamToString(responseentity.getContent());
          

        }catch(IOException ioe){
            log.error(ioe);
        }finally {
            client.getConnectionManager().shutdown();
        }
        //</editor-fold>

        String result="";
        try{
            JSONObject wfsresponse = convertToJSON(responseBody);
            JSONObject wpsresponse = convertToJSON(res);

            //log.debug(wfsresponse.toString(2));
            //log.debug(wpsresponse.toString(2));
            //String wfsReS=wfsresponse.toString(2);
           // wfsresponse.getJSONObject("")

            JSONObject featureMember = wfsresponse.getJSONObject("gml:featureMember");
            JSONObject fslatt = featureMember.getJSONObject("lcr:fsl-north-island-all-attributes");
            String drainclass = fslatt.getString("lcr:DRAIN_CLAS");
            String prawclass = fslatt.getString("lcr:PRAW_CLASS");

            JSONObject ProccessOutputs = wpsresponse.getJSONObject("ns:ProcessOutputs");
            JSONObject Output = ProccessOutputs.getJSONObject("ns:Output");
            JSONObject Data = Output.getJSONObject("ns:Data");
            JSONObject LiteralData = Data.getJSONObject("ns:LiteralData");


            result = "loadJSON({\"result\":{\"scalefactor\":\""  +LiteralData.getString("#text")+ "\","+
                    " \"drain_clas\":\""+ drainclass + "\","+
                    " \"praw_class\":\""+prawclass + "\","+
                    " \"lat\":\""+lat + "\","+
                    " \"lon\":\""+lon +"\"}})";
        }catch(net.sf.json.JSONException jse){
            jse.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
         return result;
    }

    /**
     * PUT method for updating or creating an instance of LucLookupResource
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @PUT
    @Consumes("application/json")
    public void putJson(String content) {
    }

    private String convertStreamToString(InputStream is)throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }

    private JSONObject convertToJSON(String xml)throws net.sf.json.JSONException{
        JSONObject result=null;

         XMLSerializer xmlSerializer = new XMLSerializer();

         JSON json = xmlSerializer.read( xml );
         result = (JSONObject) JSONSerializer.toJSON( json );

        return result;
    }
}